package simulation;


import force.Force;
import java.util.List;
import view.Canvas;

/**
 * Handles the logic for all user input (via mouse, keyboard...)
 * @author Dagbedji Fagnisse
 * @author Scott Valentine
 *
 */
public class UserInteraction {
    
    private Model myModel;
    private Canvas myView;
    
    /**
     * Creates a UserInteraction object for a specific model
     * @param model - the model to which the UserInteraction applies
     * @param view - the canvas linked to the model
     */
    public UserInteraction(Model model, Canvas view) {
        myModel = model;
        myView = view;
    }
    
    /**
     * checks for any keys released during current frame
     * 
     * @param canvas
     */
    public void checkInputs () {
        for (int key : myView.getKeysPressed()) {
            checkForceInputs(key, myModel.getForces());
            checkBoundsInputs(key, myModel);
            checkConstructionInputs(key, myView, myModel);
        }
        checkMouseInput(myView, myModel);
    }

    private void checkForceInputs (int key, List<Force> forces) {
        for (Force f : forces) {
            if (key == f.getToggleKey()) {
                f.toggle();
            }
        }
    }

    /**
     * looks for and applies changes in bounds of simulation
     */
    private void checkBoundsInputs (int key, Model model) {
        if (key == SpringiesConstants.INCREASE_BOUNDS) {
            model.updateBounds(+SpringiesConstants.BOUNDS_CHANGE_VALUE);
        }
        if (key == SpringiesConstants.DECREASE_BOUNDS) {
            model.updateBounds(-SpringiesConstants.BOUNDS_CHANGE_VALUE);
        }
    }

    /**
     * looks for model construction inputs
     * i.e. clearing all objects in simulation, loading a new model
     */
    private void checkConstructionInputs (int key, Canvas canvas, Model model) {
        if (key == SpringiesConstants.CLEAR_SIMULATION) {
            model.clearAssemblies();
        }
        if (key == SpringiesConstants.LOAD_SIMULATION) {
            canvas.loadAssembly();
            canvas.resetLastKey();
        }
        
    }
    
    private void checkMouseInput (Canvas canvas, Model model) {
        if (canvas.getLastMousePosition() != Canvas.NO_MOUSE_PRESSED) {
            if (!model.assembliesContainMouseElements()) {
                model.addMouseElements();
            }
        }
        else {
            model.removeMouseElements();
        }
    }

}
